import 'dart:async';
import 'package:flutter/material.dart';
import 'package:wallpaper/components/video/video_play.dart';
import 'package:async_wallpaper/async_wallpaper.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/services.dart';
import 'package:gallery_saver_plus/gallery_saver.dart';
import 'package:provider/provider.dart';
import 'package:wallpaper/components/button/action_icon_btn.dart';
import 'package:wallpaper/db/love_database.dart';
import 'package:wallpaper/generated/l10n.dart';

class VideoPageView extends StatefulWidget {
  final List videoList;
  final int activeIndex;
  final bool isLove;
  final VoidCallback resetGetdata;
  const VideoPageView({
    super.key,
    required this.videoList,
    required this.activeIndex,
    this.isLove = false,
    required this.resetGetdata,
  });

  @override
  State<VideoPageView> createState() => _VideoPageViewState();
}

class _VideoPageViewState extends State<VideoPageView> {
  late PageController _pageController;
  int _currentIndex = 0;
  bool isOperation = true;
  bool isLoveState = false;
  String _currentVideoPath = "";
  double videoRadio = 1.0;
  Timer? loadTimer;

  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: widget.activeIndex);
    _currentIndex = widget.activeIndex;
    loadTimer = Timer(const Duration(milliseconds: 300), () {
      if (mounted) {
        setState(() {
          _checkIfLoved();
        });
      }
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    loadTimer?.cancel();
    super.dispose();
  }

  void changeVideoRadio(double radio) {
    videoRadio = radio;
  }

  // 检查当前视频是否已收藏
  void _checkIfLoved() async {
    final currentVideo = widget.videoList[_currentIndex];
    final smallPath =
        widget.isLove ? currentVideo.smallPath : currentVideo.cover;
    bool res = await context.read<LoveDatabase>().isLove(smallPath);
    setState(() {
      isLoveState = res;
    });
  }

  // 获取当前视频的临时文件路径
  void updateCurrentVideoPath(String path) {
    setState(() {
      _currentVideoPath = path;
    });
  }

  // 下载视频
  void downLoad() async {
    if (_currentVideoPath.isEmpty) {
      BotToast.showText(text: S.of(context).s7);
      return;
    }
    await GallerySaver.saveVideo(_currentVideoPath);
    BotToast.showText(text: S.of(context).s1);
  }

  // 分享视频链接
  void shareImage() async {
    final currentVideo = widget.videoList[_currentIndex];
    final largePath = widget.isLove ? currentVideo.largePath : currentVideo.url;
    Clipboard.setData(ClipboardData(text: largePath));
    BotToast.showText(text: S.of(context).s2);
  }

  // 设置壁纸
  void setWallpaper() async {
    if (_currentVideoPath.isEmpty) {
      BotToast.showText(text: S.of(context).s7);
      return;
    }
    try {
      await AsyncWallpaper.setLiveWallpaper(
        filePath: _currentVideoPath,
        goToHome: false,
      );
    } on PlatformException {
      BotToast.showText(text: S.of(context).s5, backgroundColor: Colors.red);
    }
  }

  // 切换收藏状态
  void changeLove() {
    final currentVideo = widget.videoList[_currentIndex];
    final smallPath =
        widget.isLove ? currentVideo.smallPath : currentVideo.cover;
    final largePath = widget.isLove ? currentVideo.largePath : currentVideo.url;
    final tags = widget.isLove ? currentVideo.tags : currentVideo.tag;

    setState(() {
      isLoveState = !isLoveState;
    });

    // 根据视频比例确定添加方向
    String orientation = videoRadio <= 1.0 ? 'vertical' : 'horizontal';
    context.read<LoveDatabase>().addLove(
          smallPath,
          largePath,
          tags,
          'video',
          orientation,
        );

    widget.resetGetdata();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: Stack(
        children: [
          buildVideoPlay(),
          // 添加操作栏
          Positioned(
            top: 0,
            right: 12,
            bottom: 0,
            child: Center(
              child: AnimatedSlide(
                offset: isOperation ? Offset.zero : const Offset(1.5, 0),
                duration: const Duration(milliseconds: 300),
                curve: Curves.easeInOut,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    ActionIconButton(
                      icon: Icons.phone_android_rounded,
                      onTap: setWallpaper,
                      color: Colors.white,
                    ),
                    const SizedBox(height: 12),
                    ActionIconButton(
                      icon: Icons.share,
                      onTap: shareImage,
                      color: Colors.white,
                    ),
                    const SizedBox(height: 12),
                    ActionIconButton(
                      icon: Icons.download,
                      onTap: downLoad,
                      color: Colors.white,
                    ),
                    const SizedBox(height: 12),
                    ActionIconButton(
                      icon:
                          isLoveState ? Icons.favorite : Icons.favorite_border,
                      onTap: changeLove,
                      color: isLoveState ? Colors.red : Colors.white,
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget buildVideoPlay() {
    return GestureDetector(
      onTap: () {
        setState(() {
          isOperation = !isOperation;
        });
      },
      child: PageView.builder(
        scrollDirection: Axis.vertical,
        controller: _pageController,
        itemCount: widget.videoList.length,
        onPageChanged: (index) {
          if (mounted) {
            setState(() {
              _currentIndex = index;
              _currentVideoPath = ""; // 重置视频路径
            });
            _checkIfLoved(); // 检查新页面的视频是否已收藏
          }
        },
        itemBuilder: (context, index) {
          return VideoPlay(
            smallPath: widget.isLove
                ? widget.videoList[index].smallPath
                : widget.videoList[index].cover,
            largePath: widget.isLove
                ? widget.videoList[index].largePath
                : widget.videoList[index].url,
            tags: widget.isLove
                ? widget.videoList[index].tags
                : widget.videoList[index].tag,
            resetGetdata: widget.resetGetdata,
            onVideoPathUpdate:
                index == _currentIndex ? updateCurrentVideoPath : null,
            changeVideoRadio: changeVideoRadio,
          );
        },
      ),
    );
  }
}
